package cn.com.onlinetextproject.controller;

import cn.com.onlinetextproject.dao.ClassDao;
import cn.com.onlinetextproject.dao.UsersDao;
import cn.com.onlinetextproject.model.Pjclass;
import cn.com.onlinetextproject.model.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@Controller
@RequestMapping("/")
public class LoginController {
    HttpSession session;
    @Autowired
    ClassDao classDao;
    @Autowired
    UsersDao usersDao;
    @RequestMapping("/login")
    private String login(){
        return "/student/login";
    }
    @PostMapping("/CanLogin")
    private String CanLogin(String username, String userpwd,HttpServletRequest request){
        Iterable<Users> users = usersDao.findAll();
        String errorInfo = "";
        for (Users lis : users){
            if(lis.getUsername().equals(username) && lis.getUserpwd().equals(userpwd)){
               if (lis.getRoleid().equals(1)){
                   request.getSession().setAttribute("Tlis",lis);
                   Integer id = lis.getClassid();
                   request.getSession().setAttribute("Tclassid",id);
                   return "redirect:/TeacherManage";
               }else if (lis.getRoleid().equals(2)){
                   request.getSession().setAttribute("lis",lis);
                   Integer usid = lis.getUserid();
                   Integer id = lis.getClassid();
                   request.getSession().setAttribute("classid",id);
                   request.getSession().setAttribute("userid",usid);
                   return "redirect:/StuMan";
               }else if (lis.getRoleid().equals(3)){
                   request.getSession().setAttribute("Alis",lis);
                   request.getSession().setMaxInactiveInterval(30 * 60);
                   return "redirect:/AdminManage";
               }
            }else {
                errorInfo = "账号或密码错误";
                request.getSession().setAttribute("errorInfo",errorInfo);
            }

        }
        return "redirect:/login";
    }
    @GetMapping("/register")
    private  String register(Model model){
        Iterable<Pjclass> list = classDao.findAll();
        model.addAttribute("list",list);
        return "/student/register";
    }
    @PostMapping("/CanRegister")
    private String CanRegister(Integer roleid, String username, String userpwd, String truename, Integer classid, HttpServletRequest request) {
        HttpSession session = request.getSession();
        
        // Clear any previous session messages
        session.removeAttribute("wk");
        session.removeAttribute("cz");
        session.removeAttribute("cg");
        
        // Validate input data
        if (username == null || username.trim().isEmpty()) {
            session.setAttribute("wk", "用户名不能为空！");
            return "redirect:/register";
        }
        
        if (userpwd == null || userpwd.trim().isEmpty()) {
            session.setAttribute("wk", "密码不能为空！");
            return "redirect:/register";
        }
        
        if (truename == null || truename.trim().isEmpty()) {
            session.setAttribute("wk", "姓名不能为空！");
            return "redirect:/register";
        }
        
        if (classid == null) {
            session.setAttribute("wk", "请选择班级！");
            return "redirect:/register";
        }
        
        // Check if username already exists
        Users byUsername = usersDao.findByUsername(username);
        if (byUsername != null) {
            session.setAttribute("cz", "该用户名已存在！");
            return "redirect:/register";
        }
        
        // Create new user
        Users users = new Users();
        users.setRoleid(roleid);
        users.setUsername(username.trim());
        users.setUserpwd(userpwd.trim());
        users.setTruename(truename.trim());
        users.setClassid(classid);
        
        // Save user
        usersDao.save(users);
        
        // Set success message
        session.setAttribute("cg", "注册成功，请登录！");
        
        return "redirect:/register";
    }
    @RequestMapping("/StuMan")
    private String StuMan(){
        return "/student/StuMan";
    }
    //学生注销
    @RequestMapping("/logout")
    private String logout(HttpServletRequest request){
        HttpSession session = request.getSession(true);
        System.out.println("注销");
        session.removeAttribute("lis");
        session.removeAttribute("classid");
        session.removeAttribute("classid");
        session.removeAttribute("errorInfo");
        session.removeAttribute("cxdl");
        return  "redirect:/login";
    }
    //老师注销
    @RequestMapping("/Tlogout")
    private  String Tlogout(HttpServletRequest request){
        HttpSession session = request.getSession(true);
        session.removeAttribute("Tlis");
        session.removeAttribute("Tclassid");
        session.removeAttribute("Tuserid");
        return  "redirect:/login";
    }
    //管理员注销
    @RequestMapping("/Alogout")
    private  String Alogout(HttpServletRequest request){
        HttpSession session = request.getSession(true);
        session.removeAttribute("Alis");
        return  "redirect:/login";
    }
    //登录SESSION
    @RequestMapping("/llogout")
    private  String llogout(HttpServletRequest request){
        HttpSession session = request.getSession(true);
        session.removeAttribute("errorInfo");
        session.removeAttribute("cxdl");
        return  "redirect:/login";
    }
    //注册清除session
    @RequestMapping("/zclogout")
    private String zclogout(HttpServletRequest request){
        HttpSession session = request.getSession(true);
        System.out.println("注册清除ssesion成功！");
        session.removeAttribute("wk");
        session.removeAttribute("wk");
        return "redirect:/register";
    }
    
    // 显示修改密码页面
    @GetMapping("/changePassword")
    private String showChangePasswordPage() {
        return "/student/changePassword";
    }
    
    //修改密码
    @PostMapping("/xiugai")
    private String xiugai(Integer userid, String userpwd, HttpServletRequest request){
        // Validate inputs
        if (userid == null || userpwd == null || userpwd.trim().isEmpty()) {
            return "redirect:/logout";
        }
        
        // Check password length for security
        if (userpwd.length() < 6) {
            return "redirect:/logout";
        }
        
        // Update password in database
        Integer updateResult = usersDao.updatepwd(userpwd.trim(), userid);
        
        // Handle result
        if (updateResult == 1) {
            String cxdl = "cxdl";
            request.getSession().setAttribute("cxdl", cxdl);
            return "redirect:/login";
        }
        
        return "redirect:/logout";
    }
}
